
import Cesium from 'cesium';
class EntityLoader {
  private viewer: Cesium.Viewer;
  private worker: Worker;
  private batchSize = 500; // 每批加载数量
  private totalEntities = 10000;
  private loadedCount = 0;
  
  constructor(viewer: Cesium.Viewer) {
    this.viewer = viewer;
    this.worker = new Worker('./worker.js');
    
    this.worker.onmessage = this.handleWorkerMessage.bind(this);
  }
  
  // 加载所有实体
  public loadAllEntities(positions: Array<{lon: number, lat: number, height?: number}>) {
    this.loadBatch(0, positions);
  }
  
  // 加载批次
  private loadBatch(startIndex: number, positions: any[]) {
    const remaining = positions.length - startIndex;
    const count = Math.min(this.batchSize, remaining);
    
    this.worker.postMessage({
      type: 'GENERATE_ENTITIES',
      payload: {
        startIndex,
        count,
        positions
      }
    });
  }
  
  // 处理Worker返回的消息
  private handleWorkerMessage(e: MessageEvent) {
    const { type, payload } = e.data;
    
    if (type === 'ENTITIES_GENERATED') {
      const { entities, startIndex, count } = payload;
      
      // 使用Cesium的DataSource API批量添加实体
      const dataSource = new Cesium.CustomDataSource('dynamicEntities');
      entities.forEach((entity: any) => {
        dataSource.entities.add(entity);
      });
      
      this.viewer.dataSources.add(dataSource);
      this.loadedCount += count;
      
      console.log(`已加载 ${this.loadedCount}/${this.totalEntities} 个实体`);
      
      // 加载下一批
      if (this.loadedCount < this.totalEntities) {
        // 使用requestAnimationFrame避免阻塞UI
        requestAnimationFrame(() => {
          this.loadBatch(startIndex + count, positions);
        });
      }
    }
  }
  
  // 销毁时清理
  public destroy() {
    this.worker.terminate();
  }
}